﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using HIWSystem.Models;
using HIWSystem.Common;
using System.Windows;
using System.Windows.Controls;

namespace HIWSystem.ViewModel
{
    public class AddRoutingViewModel : ViewModelBase
    {
        #region 属性
        private bool IsFirstFilter = true;

        ObservableCollection<PartNumberEntity> backupPNs = null;
        private bool comboOpen;
        /// <summary>
        /// 是否打开下拉
        /// </summary>
        public bool ComboOpen
        {
            get { return comboOpen; }
            set { comboOpen = value; this.RaisePropertyChanged(() => ComboOpen); }
        }
        private string searchText;
        /// <summary>
        /// ComboBox文本框输入的搜索文本
        /// </summary>
        public string SearchText
        {
            get { return searchText; }
            set { searchText = value; this.RaisePropertyChanged(() => SearchText); }
        }
        private PartNumberEntity selectedPartNumber;
        /// <summary>
        ///  选中的机种
        /// </summary>
        public PartNumberEntity SelectedPartNumber
        {
            get { return selectedPartNumber; }
            set { selectedPartNumber = value; this.RaisePropertyChanged(() => SelectedPartNumber); }
        }

        private ObservableCollection<PartNumberEntity> pns;
        /// <summary>
        /// 机种信息
        /// </summary>
        public ObservableCollection<PartNumberEntity> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }
        private string selectedPN;
        /// <summary>
        /// 选中的机种
        /// </summary>
        public string SelectedPN
        {
            get { return selectedPN; }
            set { selectedPN = value; this.RaisePropertyChanged(() => SelectedPN); }
        }
        private ObservableCollection<StationsEntity> stations;
        /// <summary>
        /// 站位信息
        /// </summary>
        public ObservableCollection<StationsEntity> Stations
        {
            get { return stations; }
            set { stations = value; this.RaisePropertyChanged(() => Stations); }
        }
        private ObservableCollection<string> flowStations;
        /// <summary>
        /// 流程站位
        /// </summary>
        public ObservableCollection<string> FlowStations
        {
            get { return flowStations; }
            set { flowStations = value; this.RaisePropertyChanged(() => FlowStations); }
        }
        private ObservableCollection<string> productionStages;
        /// <summary>
        /// 生产阶段
        /// </summary>
        public ObservableCollection<string> ProductionStages
        {
            get { return productionStages; }
            set { productionStages = value; this.RaisePropertyChanged(() => ProductionStages); }
        }
        private string flow="";
        /// <summary>
        /// 流程
        /// </summary>
        public string Flow
        {
            get { return flow; }
            set { flow = value; this.RaisePropertyChanged(() => Flow); }
        }
        private ObservableCollection<RoutingEntity> routing_M_Source;
        /// <summary>
        /// 流程主表数据源
        /// </summary>
        public ObservableCollection<RoutingEntity> Routing_M_Source
        {
            get { return routing_M_Source; }
            set { routing_M_Source = value; this.RaisePropertyChanged(() => Routing_M_Source); }
        }
        private ObservableCollection<RoutingEntity> routing_C_Source;
        /// <summary>
        /// 流程子表数据源
        /// </summary>
        public ObservableCollection<RoutingEntity> Routing_C_Source
        {
            get { return routing_C_Source; }
            set { routing_C_Source = value; this.RaisePropertyChanged(() => Routing_C_Source); }
        }
        private string pn="";
        /// <summary>
        /// 选择的机种信息
        /// </summary>
        public string PN
        {
            get { return pn; }
            set { pn = value; this.RaisePropertyChanged(() => PN); }
        }
        private string productionStage="";
        /// <summary>
        /// 生产阶段
        /// </summary>
        public string ProductionStage
        {
            get { return productionStage; }
            set { productionStage = value; this.RaisePropertyChanged(() => ProductionStage); }
        }
        private RoutingEntity selectedChildRoutingItem;
        /// <summary>
        /// 选中子流程项
        /// </summary>
        public RoutingEntity SelectedChildRoutingItem
        {
            get { return selectedChildRoutingItem; }
            set { selectedChildRoutingItem = value; this.RaisePropertyChanged(() => SelectedChildRoutingItem); }
        }
        private string selectedPackingCheckStandard;

        public string SelectedPackingCheckStandard
        {
            get { return selectedPackingCheckStandard; }
            set { selectedPackingCheckStandard = value; this.RaisePropertyChanged(() => SelectedPackingCheckStandard); }
        }

        #endregion
        #region 命令
        private RelayCommand loadPageCmd;

        public RelayCommand LoadPageCmd
        {
            get 
            {
                if (loadPageCmd==null)
                {
                    loadPageCmd = new RelayCommand(LoadedPage);
                }
                return loadPageCmd; 
            }
            set { loadPageCmd = value; }
        }

        private RelayCommand<StationsEntity> lstStation_MouseDoubleClick;

        public RelayCommand<StationsEntity> LstStation_MouseDoubleClick
        {
            get 
            {
                if (lstStation_MouseDoubleClick==null)
                {
                    lstStation_MouseDoubleClick = new RelayCommand<StationsEntity>(LstStation_MouseDoubleClickHandler);
                }
                return lstStation_MouseDoubleClick; 
            }
            set { lstStation_MouseDoubleClick = value; }
        }
        private RelayCommand<string> lstFlowStation_MouseDoubleClick;

        public RelayCommand<string> LstFlowStation_MouseDoubleClick
        {
            get 
            {
                if (lstFlowStation_MouseDoubleClick==null)
                {
                    lstFlowStation_MouseDoubleClick = new RelayCommand<string>(LstFlowStation_MouseDoubleClickHandler);
                }
                return lstFlowStation_MouseDoubleClick; 
            }
            set { lstFlowStation_MouseDoubleClick = value; }
        }
        private RelayCommand filterCmd;

        public RelayCommand FilterCmd
        {
            get 
            {
                if (filterCmd==null)
                {
                    filterCmd = new RelayCommand(FilterPNs);
                }
                return filterCmd; 
            }
            set { filterCmd = value; }
        }
        private RelayCommand<string> comboPN_SelectionChangedCmd;

        public RelayCommand<string> ComboPN_SelectionChangedCmd
        {
            get 
            {
                if (comboPN_SelectionChangedCmd==null)
                {
                    comboPN_SelectionChangedCmd = new RelayCommand<string>(ComboPN_SelectionChangedHandler);
                }
                return comboPN_SelectionChangedCmd; 
            }
            set { comboPN_SelectionChangedCmd = value; }
        }
        private RelayCommand showFlowCmd;

        public RelayCommand ShowFlowCmd
        {
            get 
            {
                if (showFlowCmd==null)
                {
                    showFlowCmd = new RelayCommand(ShowFlow);
                }
                return showFlowCmd;
            }
            set { showFlowCmd = value; }
        }
        private RelayCommand addRoutingCmd;

        public RelayCommand AddRoutingCmd
        {
            get 
            {
                if (addRoutingCmd==null)
                {
                    addRoutingCmd = new RelayCommand(AddRouting);
                }
                return addRoutingCmd; 
            }
            set { addRoutingCmd = value; }
        }
        private RelayCommand<object> comboPackingCheckStandard_SelectionChangedCmd;

        public RelayCommand<object> ComboPackingCheckStandard_SelectionChangedCmd
        {
            get
            {
                if (comboPackingCheckStandard_SelectionChangedCmd == null)
                {
                    comboPackingCheckStandard_SelectionChangedCmd = new RelayCommand<object>(ComboPackingCheckStandard_SelectionChangedCmdHandler);
                }
                return comboPackingCheckStandard_SelectionChangedCmd;
            }
            set { comboPackingCheckStandard_SelectionChangedCmd = value; }
        }
        private RelayCommand<object> comboEndCheckStandard_SelectionChangedCmd;

        public RelayCommand<object> ComboEndCheckStandard_SelectionChangedCmd
        {
            get
            {
                if (comboEndCheckStandard_SelectionChangedCmd == null)
                {
                    comboEndCheckStandard_SelectionChangedCmd = new RelayCommand<object>(ComboEndCheckStandard_SelectionChangedCmdHandler);
                }
                return comboEndCheckStandard_SelectionChangedCmd;
            }
            set { comboEndCheckStandard_SelectionChangedCmd = value; }
        }

        private RelayCommand<object> comboShipCheckStandard_SelectionChangedCmd;

        public RelayCommand<object> ComboShipCheckStandard_SelectionChangedCmd
        {
            get
            {
                if (comboShipCheckStandard_SelectionChangedCmd == null)
                {
                    comboShipCheckStandard_SelectionChangedCmd = new RelayCommand<object>(ComboShipCheckStandard_SelectionChangedCmdHandler);
                }
                return comboShipCheckStandard_SelectionChangedCmd;
            }
            set { comboShipCheckStandard_SelectionChangedCmd = value; }
        }

        #endregion
        #region 方法
        /// <summary>
        ///  添加流程信息
        /// </summary>
        private void AddRouting()
        {
            string retMsg = string.Empty; //数据库返回的状态信息
            DataTable[] dtRoutings = new DataTable[] { };

            if (this.FlowStations==null || this.FlowStations.Count==0)
            {
                MessageBox.Show("没有添加工作流","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }
            RoutingEntity routing = new RoutingEntity {
                PN = this.PN,
                Flow = this.Flow.Trim().ToUpper(),
                ProductionStage = this.ProductionStage,
                Station = string.Join("|", this.FlowStations.ToArray()),
                SubFlow = "", //带后续再界面上增加输入框
                Actor_M=LogInInfo.User //管理系统登录的用户信息
            };
            retMsg = BusinessProcess.AddRoutings(routing, out dtRoutings);
            if (retMsg.Split('|')[0] == "OK")
            {
                Routing_M_Source = new ObservableCollection<RoutingEntity>();
                for (int i = 0; i < dtRoutings[3].Rows.Count; i++)
                {
                    Routing_M_Source.Add(
                     new RoutingEntity
                     {
                         PN = dtRoutings[3].Rows[i]["PN"].ToString(),
                         Flow = dtRoutings[3].Rows[i]["Flow"].ToString(),
                         ProductionStage = dtRoutings[3].Rows[i]["ProductionStage"].ToString(),
                         Actor_M = dtRoutings[3].Rows[i]["Actor"].ToString(),
                         CreateAt_M = dtRoutings[3].Rows[i]["CreateAt"].ToString(),
                     }); ;
                }
                Routing_C_Source = new ObservableCollection<RoutingEntity>();
                for (int i = 0; i < dtRoutings[4].Rows.Count; i++)
                {
                    Routing_C_Source.Add(new RoutingEntity
                    {
                        MId = Convert.ToInt32(dtRoutings[4].Rows[i]["MId"].ToString()),
                        Flow_C = dtRoutings[4].Rows[i]["Flow"].ToString(),
                        Sequence = Convert.ToInt32(dtRoutings[4].Rows[i]["Sequence"].ToString()),
                        Station = dtRoutings[4].Rows[i]["Station"].ToString(),
                        IsSkip = dtRoutings[4].Rows[i]["IsSkip"].ToString(),
                        SubFlow = dtRoutings[4].Rows[i]["SubFlow"].ToString(),
                        Actor_C = dtRoutings[4].Rows[i]["Actor_C"].ToString(),
                        CreateAt_C = dtRoutings[4].Rows[i]["CreateAt_C"].ToString(),
                        PackingCheckStandard = dtRoutings[4].Rows[i]["PackingCheckStandard"].ToString(),
                        EndCheckStandard = dtRoutings[4].Rows[i]["EndCheckStandard"].ToString(),
                        ShipCheckStandard = dtRoutings[4].Rows[i]["ShipCheckStandard"].ToString(),
                    });
                }
                MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void ComboPN_SelectionChangedHandler(string obj)
        {
            if (obj==null)
            {
                return;
            }
            DataTable[] dtRoutings = new DataTable[2];
            string retMsg = string.Empty;//返回的信息
            string selectedPN = string.Empty;//选择的机种

            selectedPN = obj.ToUpper();
            retMsg= BusinessProcess.GetRoutingByPN(selectedPN, out dtRoutings);
            if (retMsg.Split('|')[0] == "OK")
            {
                Routing_M_Source = new ObservableCollection<RoutingEntity>();
                for (int i = 0; i < dtRoutings[0].Rows.Count; i++)
                {
                    Routing_M_Source.Add(
                     new RoutingEntity
                     {
                         PN = dtRoutings[0].Rows[i]["PN"].ToString(),
                         Flow= dtRoutings[0].Rows[i]["Flow"].ToString(),
                         ProductionStage = dtRoutings[0].Rows[i]["ProductionStage"].ToString(),
                         Actor_M = dtRoutings[0].Rows[i]["Actor"].ToString(),
                         CreateAt_M = dtRoutings[0].Rows[i]["CreateAt"].ToString(),
                     }); ;
                }
                Routing_C_Source = new ObservableCollection<RoutingEntity>();
                for (int i = 0; i < dtRoutings[1].Rows.Count; i++)
                {
                    Routing_C_Source.Add(new RoutingEntity
                    {
                        MId = Convert.ToInt32(dtRoutings[1].Rows[i]["MId"].ToString()),
                        Flow_C = dtRoutings[1].Rows[i]["Flow"].ToString(),
                        Sequence=Convert.ToInt32(dtRoutings[1].Rows[i]["Sequence"].ToString()),
                        Station= dtRoutings[1].Rows[i]["Station"].ToString(),
                        IsSkip= dtRoutings[1].Rows[i]["IsSkip"].ToString(),
                        SubFlow= dtRoutings[1].Rows[i]["SubFlow"].ToString(),
                        Actor_C= dtRoutings[1].Rows[i]["Actor_C"].ToString(),
                        CreateAt_C= dtRoutings[1].Rows[i]["CreateAt_C"].ToString(),
                        PackingCheckStandard = dtRoutings[1].Rows[i]["PackingCheckStandard"].ToString(),
                        EndCheckStandard = dtRoutings[1].Rows[i]["EndCheckStandard"].ToString(),
                        ShipCheckStandard = dtRoutings[1].Rows[i]["ShipCheckStandard"].ToString(),
                    });
                }
               // MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        private void ShowFlow()
        {
            string retMsg = string.Empty;
            DataTable dtRouting = new DataTable();
            if (Flow=="")
            {
                MessageBox.Show("流程信息不能为空!","软件温馨提示!",MessageBoxButton.OK,MessageBoxImage.Warning);
                return;
            }

            retMsg = BusinessProcess.GetRoutingByFlow(Flow, out dtRouting);
            if (retMsg.Split('|')[0] == "OK")
            {
                Routing_C_Source = new ObservableCollection<RoutingEntity>();
                for (int i = 0; i < dtRouting.Rows.Count; i++)
                {
                    Routing_C_Source.Add(
                     new RoutingEntity
                     {
                         MId = Convert.ToInt32(dtRouting.Rows[i]["MId"].ToString()),
                         Flow_C = dtRouting.Rows[i]["Flow"].ToString(),
                         Sequence =Convert.ToInt32(dtRouting.Rows[i]["Sequence"].ToString()),
                         Station= dtRouting.Rows[i]["Station"].ToString(),
                         IsSkip= dtRouting.Rows[i]["IsSkip"].ToString(),
                         SubFlow= dtRouting.Rows[i]["SubFlow"].ToString(),
                         Actor_C= dtRouting.Rows[i]["Actor_C"].ToString(),
                         PackingCheckStandard= dtRouting.Rows[i]["PackingCheckStandard"].ToString(),
                         EndCheckStandard = dtRouting.Rows[i]["EndCheckStandard"].ToString(),
                         ShipCheckStandard= dtRouting.Rows[i]["ShipCheckStandard"].ToString(),
                         CreateAt_C = dtRouting.Rows[i]["CreateAt_C"].ToString()
                     }); ;
                }
                //MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show(retMsg.Split('|')[1].ToString(), "软件温馨提示!", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }
        protected void FilterPNs()
        {
            ComboOpen = true;
            //当是第一次过滤的时候备份原始数据
            //这样是为了当不输入搜索条件时添加原始数据到列表中
            //当输入搜索条件时生成过滤集合绑定当下拉列表中
            if (IsFirstFilter)
            {
                backupPNs = new ObservableCollection<PartNumberEntity>();
                backupPNs = PNs;
                IsFirstFilter = false;
            }
            //backupPNs = PNs;
            if (!string.IsNullOrEmpty(SearchText))
            {
                IEnumerable<PartNumberEntity> partNumberEntities= PNs.Where(s => s.PN.ToUpper().Contains(SearchText.ToUpper()));
                PNs = new ObservableCollection<PartNumberEntity>();
                foreach (var p in partNumberEntities)
                {
                    PNs.Add(p);
                }
            }
            else
            {
                PNs = backupPNs;
            }
            //OnPropertyChanged("Shops");
        }
        private void LoadedPage()
        {
            //填充机种信息到下拉列表框中
            this.FillPNsToComboBox();
            //填充站位信息到列表框中
            this.FillStationsToListBox();
            //填充生产阶段信息到下拉列表框中
            this.FillProductionStagesToComboBox();
        }
        private void FillPNsToComboBox()
        {
            #region 验证使用
            //PNs = new ObservableCollection<PartNumberEntity>();
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "MEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "SEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "REST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "BEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "AEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "OEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "NEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "MEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "REST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "TEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "WEST1-AAA" });
            //PNs.Add(new PartNumberEntity { PN = "XEST1-AAA" });
            #endregion
            DataTable dtPNs = new DataTable();
            dtPNs = BusinessProcess.GetPNs(EnumPNType.All);
            PNs = new ObservableCollection<PartNumberEntity>();
            for (int i = 0; i < dtPNs.Rows.Count; i++)
            {
                PNs.Add(new PartNumberEntity
                {
                    PN = dtPNs.Rows[i]["PartNumber"].ToString()
                });
            }
        }
        private void FillStationsToListBox()
        {
            DataTable dtStations = new DataTable();
            dtStations = BusinessProcess.GetStations(EnumStationType.All);
            Stations = new ObservableCollection<StationsEntity>();
            for (int i = 0; i < dtStations.Rows.Count; i++)
            {
                Stations.Add(new StationsEntity
                {
                    Station = dtStations.Rows[i]["Station"].ToString(),
                    StationDesc = dtStations.Rows[i]["Description"].ToString(),
                    StationType = dtStations.Rows[i]["Type"].ToString()
                }) ;
            }
        }
        private void FillProductionStagesToComboBox()
        {
            DataTable dtStages = new DataTable();
            dtStages = BusinessProcess.GetProductionStages();
            ProductionStages = new ObservableCollection<string>();
            for (int i = 0; i < dtStages.Rows.Count; i++)
            {
                productionStages.Add(dtStages.Rows[i]["StageName"].ToString());
            }
        }
        private void LstStation_MouseDoubleClickHandler(StationsEntity obj)
        {
            if (FlowStations is null)
                FlowStations = new ObservableCollection<string>();
            if (!FlowStations.Contains(obj.Station))
                FlowStations.Add(obj.Station);
            //MessageBox.Show("选中了站位【" + obj.Station + "】");
        }

        private void LstFlowStation_MouseDoubleClickHandler(string obj)
        {
            FlowStations.Remove(obj);
            //MessageBox.Show("选中了站位【"+obj+"】");
        }
        //设置包装站位对于每个站位的检测标准<全检、抽检、NA>
        private void ComboPackingCheckStandard_SelectionChangedCmdHandler(object standard)
        {
            var standardValue = (standard as ComboBoxItem)?.Content.ToString();
            if (standardValue != null)
            {
                SetStationCheckStandard("PACKING", standardValue);
            }
        }
        //设置出货站位对于每个站位的检测标准<全检、抽检、NA>
        private void ComboShipCheckStandard_SelectionChangedCmdHandler(object standard)
        {
            var standardValue = (standard as ComboBoxItem)?.Content.ToString();
            if (standardValue != null)
            {
                SetStationCheckStandard("SHIP", standardValue);
            }
        }
        //设置入库站位对于每个站位的检测标准<全检、抽检、NA>
        private void ComboEndCheckStandard_SelectionChangedCmdHandler(object standard)
        {
            var standardValue = (standard as ComboBoxItem)?.Content.ToString();
            if (standardValue != null)
            {
                SetStationCheckStandard("END", standardValue);
            }
        }

        private void SetStationCheckStandard(string finalCheckStation,string standard)
        {
            Task.Run(() => {
                BusinessProcess.AddStationCheckStandard(finalCheckStation, standard, SelectedChildRoutingItem);
            });
        }
        #endregion
    }
}